/**
 * Created by liguangsong on 16/8/15.
 */
$(document).ready(function() {
    getGoodsInfo();
});


function getGoodsInfo() {
    $.ajax({
        url: '../goodsInfo.json',
        success: function (result) {
            showGoodsInfo(result);
            addButtonClickEvent(result.goodsInfo);
        },
        error: function (result) {
            alert(result);
        }
    })
}


function showGoodsInfo(goods) {
    var goodsTemplate = $("#goods_template").html();
    Mustache.parse(goodsTemplate);
    var goodsInfo = Mustache.render(goodsTemplate, goods);
    $(".goods_info thead").after(goodsInfo);
}


function addButtonClickEvent(goods) {
    $("tr button").click(function() {
        var id = this.id;
        var sameIndex = searchSameGoodIndex(goods, id);
        var good = goods[sameIndex];
        saveGoodToLocal(good);
        modifyShopCarNumber();
    })
}

function saveGoodToLocal(good) {
    var shoppingCartInfo = getLocalData();
    var sameIndex = searchSameGoodIndex(shoppingCartInfo, good["id"]);
    shoppingCartInfo[sameIndex] = shoppingCartInfo[sameIndex] || good;
    shoppingCartInfo[sameIndex]["count"] = (shoppingCartInfo[sameIndex]["count"] || 0) + 1;
    shoppingCartInfo[sameIndex]["subtotal"] = calcSubtotalPrice(shoppingCartInfo[sameIndex]);
    window.localStorage.setItem("shoppingCart", JSON.stringify(shoppingCartInfo));
}

function searchSameGoodIndex(shopGood , id) {
    for (var i = 0; i < shopGood.length; i++) {
        if (shopGood[i]["id"] == id) {
            return i;
        }
    }
    return shopGood.length;
}


function calcSubtotalPrice(info) {
    var number = info["count"];
    var price = number * info["price"];
    if (number > 2 && info["discount"]==true) {
        number = info["count"] - parseInt(info["count"] / 3);
        var realPrice = number * info["price"];
        return realPrice + "元(原价：" + price + "元)";
    }
    else {
        return price + "元";
    }
}





